package com.hancher.gamelife2.scan;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.hancher.common.androidutil.AsyncUtils;
import com.hancher.common.androidutil.ClipboardUtil;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.MmkvUtil;
import com.hancher.common.androidutil.ToastUtil;
import com.hancher.common.androidutil.UriUtil;
import com.hancher.common.base.BaseFragment;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.gamelife2.R;
import com.hancher.gamelife2.databinding.FragmentScanBinding;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.journeyapps.barcodescanner.ScanContract;
import com.journeyapps.barcodescanner.ScanOptions;
import com.kongzue.dialogx.dialogs.MessageDialog;

import cn.bingoogolapple.qrcode.core.QRCodeView;

/**
 * 描述 : 扫码功能 <br/>
 * 时间 : 2024/4/16 17:27 <br/>
 * 作者 : Hancher ytu_shaoweijie@163.com
 */
public class ScanFragment extends BaseFragment<FragmentScanBinding> {

    public static final String QR_CODE = "QR_CODE";
    // 打开camera拍照
    private final ActivityResultLauncher<ScanOptions> barcodeLauncher = registerForActivityResult(new ScanContract(),
            result -> {
                if (result.getContents() == null) {
                    ToastUtil.show("已经取消");
                } else {
                    binding.editTextText.setText(result.getContents());
                    generateImage();
                    showResultDialog(result.getContents());
                }
            });
    private final ActivityResultLauncher selectPicture = registerForActivityResult(new ActivityResultContracts.OpenDocument(),
            result -> {
                String path = UriUtil.getPathByUri(getContext(), result);
                AsyncUtils.run(emitter -> {
                            String result1 = QRCodeParseUtils.syncDecodeQRCode(path);
                            emitter.onNext(result1);
                            emitter.onComplete();
                        },
                        (String result2) -> {
                            binding.editTextText.setText(result2);
                            generateImage();
                            showResultDialog(result2);
                        },
                        LogUtil::e);
            });

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 点击进行扫描二维码
        binding.btnScan.setOnClickListener(view -> {
            ScanOptions options = new ScanOptions()
                    .setDesiredBarcodeFormats(ScanOptions.QR_CODE)
                    .setPrompt("请对准二维码")
                    .setCameraId(0)
                    .setBeepEnabled(true)
                    .setOrientationLocked(false)
                    .setBarcodeImageEnabled(true);
            barcodeLauncher.launch(options);
        });
        // 点击进行扫描条形码
        binding.btnScan2.setOnClickListener(view -> {
            ScanOptions options = new ScanOptions()
                    .setDesiredBarcodeFormats(ScanOptions.ONE_D_CODE_TYPES)
                    .setPrompt("请对准条形码")
                    .setCameraId(0)
                    .setBeepEnabled(true)
                    .setOrientationLocked(false)
                    .setBarcodeImageEnabled(true);
            barcodeLauncher.launch(options);
        });

        //图片选择
        binding.btnSelect.setOnClickListener(view -> {
            selectPicture.launch(new String[]{"image/*"});
        });

        // 二维码生成
        binding.btnGenerate.setOnClickListener(view -> {
            generateImage();
        });
        binding.editTextText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                MmkvUtil.put(QR_CODE, s.toString());
            }
        });
        initCamera();
    }

    @Override
    protected void initData() {
        String qr = MmkvUtil.getString(QR_CODE, "");
        if (EmptyUtil.isNotEmpty(qr)) {
            binding.editTextText.setText(qr);
        }
        generateImage();
    }

    @Override
    protected void initListener() {
    }

    @Override
    public void onStop() {
        binding.zxingview.stopCamera();
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        binding.zxingview.onDestroy();
        super.onDestroyView();
    }

    public void showResultDialog(String result) {
        MessageDialog.build()
                .setTitle("二维码扫描内容")
                .setMessage(result)
                .setOkButton("确定并复制", (dialog, v) -> {
                    ClipboardUtil.copy(result);
                    return false;
                })
                .show();
    }

    private void initCamera() {

        binding.zxingview.hiddenScanRect();//扫描框
        binding.zxingview.setDelegate(new QRCodeView.Delegate() {
            @Override
            public void onScanQRCodeSuccess(String result) {
                binding.editTextText.setText(result);
                ToastUtil.show("扫描成功:" + result);
                AsyncUtils.runCountdownOnce(1000L, () -> binding.zxingview.startSpot());
            }

            @Override
            public void onCameraAmbientBrightnessChanged(boolean isDark) {

            }

            @Override
            public void onScanQRCodeOpenCameraError() {

            }
        });
        binding.btnOpenCamera.setOnClickListener(v -> {
            // 权限检查

            XXPermissions.with(this)
                    .permission(Permission.CAMERA)
                    .request((permissions, allGranted) -> {
                        if (allGranted) {
                            binding.zxingview.startSpot();
                        } else {
                            ToastUtil.show("权限未全部同意！");
                        }
                    });
        });
        binding.btnCloseCamera.setOnClickListener(v -> {
            binding.zxingview.stopSpot();
            binding.zxingview.stopCamera();
        });
    }

    private void generateImage() {
        try {
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            Bitmap bitmap = barcodeEncoder.encodeBitmap(binding.editTextText.getText().toString(), BarcodeFormat.QR_CODE, 800, 800);
            binding.imageQc.setImageBitmap(bitmap);
        } catch (WriterException e) {
            LogUtil.e(e.getMessage());
        }
        try {
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            Bitmap bitmap = barcodeEncoder.encodeBitmap(binding.editTextText.getText().toString(), BarcodeFormat.CODE_128, 1000, 200);
            binding.imageBar.setImageBitmap(bitmap);
        } catch (WriterException e) {
            LogUtil.e(e.getMessage());
            ToastUtil.show("转换二维码失败");
            binding.imageBar.setImageDrawable(getResources().getDrawable(R.drawable.icon_scan));
        }
    }


}